package com.srzk.youthleagueback.controller;

import com.srzk.youthleagueback.pojo.User;
import com.srzk.youthleagueback.results.CodeMsg;
import com.srzk.youthleagueback.results.Result;
import com.srzk.youthleagueback.service.UserService;
import com.srzk.youthleagueback.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 登录
     * @RequestParam userName
     * @RequestParam password
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
        return userService.login(userName, password);
    }

    /**
     * 注册
     * @RequestParam userName
     * @RequestParam password
     * @RequestParam uid
     * @RequestParam college
     * @RequestParam className
     * @return
     */
    @PostMapping("/register")
    public Result<String> register(@RequestParam("userName") String userName,
                                   @RequestParam("password") String password,
                                   @RequestParam("uid") int uid,
                                   @RequestParam("college") String college,
                                   @RequestParam("className") String className,
                                   @RequestParam("grade") String grade) {

        User user = userService.getByUserName(userName);

        if (null != user) {
            // 用户名已经存在，抛出异常
            return Result.error(CodeMsg.USERNAME_NOT_EXIST);
        }

        user = new User();
        user.setUserName(userName);
        // 注意存在数据库中的是提交的表单再加密的DBPass
        user.setPassword(MD5Util.formPassToDBPass(password));
        user.setClassName(className);
        user.setCollege(college);
        user.setUid(uid);
        user.setGrade(grade);

        userService.setUser(user);
        return Result.success("注册成功！");
    }
}
